package com.wuda.dao;

import com.wuda.bean.Book;
import com.wuda.utils.Base;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class BookDao {
	private final BookReviewDao bookReviewDao = new BookReviewDao();

	/**
	 * 搜索所有图书
	 *
	 * @param title  图书标题
	 * @param limit  每页显示的图书数量
	 * @param offset 偏移量，用于分页
	 * @return 图书列表
	 */
	public List<Book> searchBooks(String title, int limit, int offset) {
		List<Book> books = new ArrayList<>();
		Connection connection = null;
		ResultSet resultSet = null;
		try {
			connection = Base.getConnection();
			String sql = "SELECT * FROM book";
			if (title != null && !title.trim().isEmpty()) {
				sql += " WHERE title LIKE ?";
			}
			sql += " LIMIT ? OFFSET ?";
			PreparedStatement pstmt = connection.prepareStatement(sql);

			int paramIndex = 1;

			if (title != null && !title.trim().isEmpty()) {
				pstmt.setString(paramIndex++, "%" + title + "%");
			}

			pstmt.setInt(paramIndex++, limit);
			pstmt.setInt(paramIndex, offset);

			System.out.println("此时的sql为"+pstmt.toString());
			resultSet = pstmt.executeQuery();

			while (resultSet.next()) {
				Book book = new Book();
				book.setBookId(resultSet.getInt("book_id"));
				book.setTitle(resultSet.getString("title"));
				book.setAuthor(resultSet.getString("author"));
				book.setIsbn(resultSet.getString("isbn"));
				book.setPublisher(resultSet.getString("publisher"));
				book.setPublishDate(resultSet.getDate("publish_date"));
				book.setStockQuantity(resultSet.getInt("stock_quantity"));
				book.setType(resultSet.getString("type"));
				book.setIntroduce(resultSet.getString("introduce"));
				books.add(book);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				Base.closeResource(connection, null, resultSet);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return books;
	}

	/**
	 * 获取书本总数。
	 *
	 * @param title 书本的标题。
	 * @return 书本总数。
	 */
	public int getBookCount(String title) {
		Connection connection = null;
		ResultSet resultSet = null;
		int count = 0;
		try {
			connection = Base.getConnection();
			String sql = "SELECT COUNT(*) AS count FROM book";
			if (title != null && !title.trim().isEmpty()) {
				sql += " WHERE title LIKE ?";
			}
			PreparedStatement pstmt = connection.prepareStatement(sql);
			if (title != null && !title.trim().isEmpty()) {
				pstmt.setString(1, "%" + title + "%");
			}
			resultSet = pstmt.executeQuery();
			if (resultSet.next()) {
				count = resultSet.getInt("count");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				Base.closeResource(connection, null, resultSet);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return count;
	}

	/**
	 * 根据书本ID获取书本信息。
	 *
	 * @param bookId 书本的唯一标识符。
	 * @return 如果找到对应的书本，则返回该书本对象；如果没有找到或发生异常，则返回null。
	 */
	public Book getBookById(int bookId) {
		Connection connection = null;
		ResultSet resultSet = null;
		try {
			connection = Base.getConnection();
			String sql = "SELECT * FROM book WHERE book_id = ?";
			resultSet = Base.executeQuery(connection, sql, new Object[]{bookId});
			if (resultSet.next()) {
				Book book = new Book();
				book.setBookId(resultSet.getInt("book_id"));
				book.setTitle(resultSet.getString("title"));
				book.setAuthor(resultSet.getString("author"));
				book.setIsbn(resultSet.getString("isbn"));
				book.setPublisher(resultSet.getString("publisher"));
				book.setPublishDate(resultSet.getDate("publish_date"));
				book.setStockQuantity(resultSet.getInt("stock_quantity"));
				book.setType(resultSet.getString("type"));
				book.setIntroduce(resultSet.getString("introduce"));
				book.setReviews(bookReviewDao.getReviewsByBookId(bookId));
				return book;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				Base.closeResource(connection, null, resultSet);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * 根据书本ID删除图书信息。
	 *
	 * @param bookId 书本的唯一标识符。
	 * @return 如果删除成功或已存在，则返回true；否则返回false。
	 */
	public boolean deleteBookById(int bookId) {
		Connection connection = null;
		try {
			connection = Base.getConnection();
			String sql = "DELETE FROM book WHERE book_id = ?";
			int result = Base.executeUpdate(connection, sql, new Object[]{bookId});
			return result > 0;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				Base.closeResource(connection, null, null);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return false;
	}


	/**
	 * 更新图书信息。
	 *
	 * @param book 包含更新后的图书信息的对象。
	 * @return 如果更新成功（即影响的行数大于0），返回true；否则返回false。
	 */
	public boolean updateBook(Book book) {
		Connection connection = null;
		PreparedStatement pstmt = null;
		try {
			connection = Base.getConnection();
			String sql = "UPDATE book SET title = ?, author = ?, isbn = ?, publisher = ?, publish_date = ?, stock_quantity = ?, type = ?, introduce = ? WHERE book_id = ?";
			pstmt = connection.prepareStatement(sql);
			pstmt.setString(1, book.getTitle());
			pstmt.setString(2, book.getAuthor());
			pstmt.setString(3, book.getIsbn());
			pstmt.setString(4, book.getPublisher());
			pstmt.setDate(5, new java.sql.Date(book.getPublishDate().getTime()));
			pstmt.setInt(6, book.getStockQuantity());
			pstmt.setString(7, book.getType());
			pstmt.setString(8, book.getIntroduce());
			pstmt.setInt(9, book.getBookId());
			int rowsUpdated = pstmt.executeUpdate();
			return rowsUpdated > 0;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			try {
				Base.closeResource(connection, pstmt, null);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}


	/**
	 * 添加图书
	 *
	 * @param book 图书对象
	 * @return 如果添加成功（即影响的行数大于0），返回true；否则返回false。
	 */
	public boolean addBook(Book book) {
		Connection connection = null;
		PreparedStatement pstmt = null;

		try {
			connection = Base.getConnection();
			String sql = "INSERT INTO book (title, author, isbn, publisher, publish_date, stock_quantity, type, introduce) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
			pstmt = connection.prepareStatement(sql);

			pstmt.setString(1, book.getTitle());
			pstmt.setString(2, book.getAuthor());
			pstmt.setString(3, book.getIsbn());
			pstmt.setString(4, book.getPublisher());
			pstmt.setDate(5, new java.sql.Date(book.getPublishDate().getTime()));

			pstmt.setInt(6, book.getStockQuantity());
			pstmt.setString(7, book.getType());
			pstmt.setString(8, book.getIntroduce());

			int rowsInserted = pstmt.executeUpdate();
			return rowsInserted > 0;
		} catch (SQLException | ClassNotFoundException e) {
			// 记录异常信息到日志文件或者其他适当的地方
			e.printStackTrace();
			return false;
		} finally {
			try {
				Base.closeResource(connection, pstmt, null);
			} catch (SQLException e) {
				// 记录异常信息到日志文件或者其他适当的地方
				e.printStackTrace();
			}
		}
	}

}
